package com.server.questionbank.snframe.service.UsersService.Impl;

import com.server.questionbank.snframe.config.interceptor.JwtInterceptor;
import com.server.questionbank.snframe.domain.Course.Result.CourseFigures;
import com.server.questionbank.snframe.domain.Course.TCourse;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.mapper.TUserMapper;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.AvatarProcessing;
import com.server.questionbank.snframe.util.MinIo.MinIoBucket;
import com.server.questionbank.snframe.util.MinIo.MinIoFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private MinIoFactory minIoFactory;

    // 查询所有用户
    @Override
    public List<TUser> selectAllUser() {
        return tUserMapper.selectAllUser();
    }

    // 根据手机号查询用户
    @Override
    public TUser selectUserByPhoneNumber(String phoneNumber) {
        return tUserMapper.selectUserByPhoneNumber(phoneNumber);
    }
    // 根据手机号和密码验证登录
    @Override
    public Long selectUserByPhoneNumber(String phoneNumber, String password) {
        return tUserMapper.selectUserByPhoneNumberAndPassword(phoneNumber, password);
    }

    // 根据id查询用户
    @Override
    public TUser selectUserById(Long userId) {
        TUser tUser = tUserMapper.selectUserById(userId);
        if (tUser == null) { return null; }
        // 密码不返回
        tUser.setPasswordHash("******");
        return tUser;
    }

    // 获取用户课程数
    @Override
    public Long getStudentCount(Long userId) {
        return tUserMapper.getStudentCount(userId);
    }

    // 获取用户课程数
    @Override
    public Long getCourseCount(Long userId) {
        return tUserMapper.getCourseCount(userId);
    }

    // 获取用户创建课程
    @Override
    public List<CourseFigures> getCreateCourse(Long userId) {
        return tUserMapper.getCreateCourse(userId);
    }

    // 获取用户加入课程
    @Override
    public List<CourseFigures> getJoinCourse(Long userId) {
        return tUserMapper.getJoinCourse(userId);
    }

    // 获取用户收藏课程
    @Override
    public List<CourseFigures> getCollectCourse(Long userId) {
        return tUserMapper.getCollectCourse(userId);
    }

    // 获取当前登录用户
    @Override
    public TUser getLoginUser() {
        Long userId = -1L;
        try {
            userId = Long.valueOf(JwtInterceptor.getCurrentUser());
        } catch (Exception e) { return null; }
        if (userId == null || userId <= 0) { return null; }
        return selectUserById(userId);
    }

    // 创建用户
    @Override
    public Boolean insertUser(TUser newUser) {
        return tUserMapper.insertUser(newUser) > 0;
    }

    // 修改用户头像
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public void updateUserAvatar(Long userId, String avatarData) {
        if (avatarData == null || avatarData.isBlank()) {
            throw new IllegalArgumentException("❌ avatarData 不能为空");
        }
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("❌ userId 不正确");
        }
        try {
            MinIoBucket minIoBucket = minIoFactory.openBucket("user", true);

            // 解析头像类型和数据
            Pattern pattern = Pattern.compile("data:(image/\\w+);base64,");
            Matcher matcher = pattern.matcher(avatarData);
            String avatarName = "";
            if (matcher.find())
            {
                // 处理封面
                try
                {
                    avatarData = AvatarProcessing.AvatarProcessing(avatarData, 60, 60);
                } catch (Exception e){ throw new RuntimeException("头像处理失败", e); }
                if (avatarData == null) throw new RuntimeException("头像处理失败");

                // 判断历史头像
                List<String> files = minIoBucket.listFiles(userId + "/avatar/");
                avatarName = "avatar_" + String.valueOf(files.size()) + ".png";
                // 删除最古老的头像
                if (files.size() >= 5)
                {
                    String oldest = files.get(0);
                    minIoBucket.deleteFile(oldest);
                    avatarName = MinIoBucket.getFileName(oldest); // 只取文件名（avatar_X.png）
                }

                // 解码Base64数据
                int commaIndex = avatarData.indexOf(",");
                byte[] fileBytes = Base64.getDecoder().decode(avatarData.substring(commaIndex + 1));
                InputStream fileInputStream = new ByteArrayInputStream(fileBytes);

                // 修改用户头像
                if (tUserMapper.updateUserAvatar(userId, avatarName) <= 0)
                    throw new RuntimeException("修改用户头像失败");

                // 上传新头像
                minIoBucket.uploadFile(userId + "/avatar/" + avatarName, fileInputStream, "image/png", 0);
            }
            else
            {
                // 判断历史头像是否存在
                if (!minIoBucket.fileExists(userId + "/avatar/" + avatarData))
                    throw new IllegalArgumentException("头像格式不正确"); // 历史头像不存在，并且格式不正确 抛出异常
                avatarName = avatarData;

                // 修改用户头像
                if (tUserMapper.updateUserAvatar(userId, avatarName) <= 0)
                    throw new RuntimeException("修改用户头像失败");
            }

        } catch (Exception e) {
            throw new RuntimeException("上传文件失败", e);
        }
    }
}
